Page({
  data: {
    level: 1,
    colors: [],
    targetIndex: 0,
    message: '',
    showCheckmark: false,
    showCross: false,
    userIndex: -1,
    blockCount: 4,
    maxLevel: 5,
    gridColumns: 2,
    errorCount: 0,
    timer: 10,
    timerId: null
  },

  onLoad() {
    this.startGame();
  },

  onUnload() {
    if (this.data.timerId) {
      clearInterval(this.data.timerId);
    }
  },

  // 开始游戏
  startGame() {
    const { level } = this.data;
    // 根据关卡设置不同的色块数量
    const blockCount = (level+1) * (level+1); // 第一关4个(2x2)，第二关9个(3x3)，以此类推
    const gridColumns = Math.floor(Math.sqrt(blockCount)); // 计算网格列数
    const baseColor = this.generateRandomColor();
    const targetColor = this.generateSimilarColor(baseColor);
    const targetIndex = Math.floor(Math.random() * blockCount);

    const colors = new Array(blockCount).fill(baseColor);
    colors[targetIndex] = targetColor;

    this.setData({
      colors,
      targetIndex,
      message: '请点击颜色不同的色块',
      showCheckmark: false,
      showCross: false,
      userIndex: -1,
      blockCount,
      gridColumns,
      timer: 10 // 重置倒计时
    });

    // 启动倒计时
    this.startTimer();
  },

  // 启动倒计时
  startTimer() {
    if (this.data.timerId) {
      clearInterval(this.data.timerId);
    }

    const timerId = setInterval(() => {
      const { timer } = this.data;
      if (timer > 0) {
        this.setData({ timer: timer - 1 });
      } else {
        clearInterval(timerId);
        this.handleTimeout();
      }
    }, 1000);

    this.setData({ timerId });
  },

  // 处理倒计时结束
  handleTimeout() {
    wx.showModal({
      title: '提示',
      content: '时间到，游戏失败！',
      showCancel: false,
      success: () => {
        this.setData({
          level: 1,
          errorCount: 0
        });
        this.startGame();
      }
    });
  },

  // 检查用户点击的色块
  checkColor(e) {
    const { targetIndex, level, maxLevel, errorCount } = this.data;
    const userIndex = e.currentTarget.dataset.index;

    if (userIndex === targetIndex) {
      this.setData({
        showCheckmark: true,
        message: '正确！',
        errorCount: 0 // 重置错误次数
      });

      setTimeout(() => {
        if (level === maxLevel) {
          this.setData({ message: '恭喜你，通关了！' });
        } else {
          this.setData({
            level: level + 1,
            showCheckmark: false
          });
          this.startGame();
        }
      }, 1000);
    } else {
      const newErrorCount = errorCount + 1;
      this.setData({
        showCross: true,
        userIndex,
        message: `错误，还有 ${3 - newErrorCount} 次机会！`,
        errorCount: newErrorCount
      });

      setTimeout(() => {
        if (newErrorCount >= 3) {
          wx.showModal({
            title: '提示',
            content: '三次选择错误，将回到第一关！',
            showCancel: false,
            success: () => {
              this.setData({
                level: 1,
                showCross: false,
                errorCount: 0 // 重置错误次数
              });
              this.startGame();
            }
          });
        } else {
          this.setData({
            showCross: false
          });
        }
      }, 1000);
    }
  },

  // 重新开始游戏
  restartGame() {
    this.setData({
      level: 1,
      message: ''
    });
    this.startGame();
  },

  // 生成随机颜色
  generateRandomColor() {
    const r = Math.floor(Math.random() * 256);
    const g = Math.floor(Math.random() * 256);
    const b = Math.floor(Math.random() * 256);
    return `rgb(${r}, ${g}, ${b})`;
  },

  // 生成相似颜色
  generateSimilarColor(baseColor) {
    const [r, g, b] = baseColor.match(/\d+/g).map(Number);
    const delta = 10;
    const newR = Math.min(255, Math.max(0, r + (Math.random() > 0.5 ? delta : -delta)));
    const newG = Math.min(255, Math.max(0, g + (Math.random() > 0.5 ? delta : -delta)));
    const newB = Math.min(255, Math.max(0, b + (Math.random() > 0.5 ? delta : -delta)));
    return `rgb(${newR}, ${newG}, ${newB})`;
  }
});